package com.wn.system.component;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.wn.common.model.dto.bank.BankCardRequestDTO;
import com.wn.system.entity.UserCard;
import com.wn.system.entity.UserDetail;
import com.wn.system.mapper.UserCardMapper;
import com.wn.system.mapper.UserDetailMapper;
import com.wn.system.service.IUserCardService;
import com.wn.system.service.IUserDetailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

/**
 * @author yellow Docter
 * @date 2023 -03-02
 * @desc
 */
@Component
@Slf4j
public class NotifyConsumer {


    @Autowired
    private IUserDetailService userDetailService;

    @Autowired
    private IUserCardService userCardService;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(name = "queue-bank"),
                    exchange = @Exchange(
                            name = "exchange-topic",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "notify.topic.bank"
            )
    )
    public void handlerMsg(@Payload BankCardRequestDTO bankCardRequestDTO){

        //01 拿到回调信息
        log.info("银行回调信息,===>{}",bankCardRequestDTO);

        String userCode = bankCardRequestDTO.getUserCode();

        //02 更新 userDetail
        UserDetail userDetail = userDetailService.getOne(Wrappers.lambdaQuery(UserDetail.class)
                .eq(UserDetail::getUserCode,userCode));

        userDetailService.update(Wrappers.lambdaUpdate(UserDetail.class)
                .set(UserDetail::getCardBindStatus,1)
                .eq(UserDetail::getUserCode,userCode)
        );
        log.info("更新 userDetail 绑卡状态...");

        //03  更新 userCard
        Long userId = userDetail.getId();

        userCardService.update(Wrappers.lambdaUpdate(UserCard.class)
                .set(UserCard::getBankNo,bankCardRequestDTO.getBankNo())
                .set(UserCard::getBankTitle,bankCardRequestDTO.getBankTitle())
                .set(UserCard::getStatus,1)
                .eq(UserCard::getUserId,userId)
        );
        log.info("更新 userCard 绑卡状态...");
    }

}
